<?php
require_once "includes/class/member_management.class.php";
require_once('AmazonAPI/.config.inc.php');
require_once('AmazonAPI/CBUI/CBUIRecipientTokenPipeline.php');

$userInfo=mysql_fetch_array(mysql_query("select * from tbl_users where user_id='".$_SESSION['user_id_sess']."'"));
if($userInfo['set_api']=='No')
{
echo '<script>window.location.href="index.php?amazon_land";</script>';
}
else
{
?>

<script>
function show_up()
{
    var ntop = (( $(window).height() - $('#submit').height()) / 2+$(window).scrollTop()) - 100;
    var nleft = ( $(window).width() - $('#submit').width()) / 2+$(window).scrollLeft() -200;

    $('#set_inventory_cf1').css({'left':nleft, 'top':ntop});
    $('#set_inventory_cf1').fadeIn('slow');
//    $('#proceedbtn').click(
//      function() {
//	var frm = document.getElementById('formUpload');
//		
//	    frm.submit();
//      }
//    );
   // $('#proceedbtn').attr('onclick','window.location="index.php?mySwapen&post_ownprod='+productId+'";');
}
</script>

<?php
$sql_user="Select * from tbl_users where user_id='".$_SESSION['user_id_sess']."'";
$res_user=mysql_query($sql_user);
$row_user=mysql_fetch_array($res_user);
$tokenID=$row_user['tokenID'];

if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
		$signature = $_REQUEST['signature'];
		$refundTokenID = $_REQUEST['refundTokenID'];
		$signatureVersion = $_REQUEST['signatureVersion'];
		$signatureMethod = $_REQUEST['signatureMethod'];
		$certificateUrl = $_REQUEST['certificateUrl'];
		$tokenID = $_REQUEST['tokenID'];
		$callerReference = $_REQUEST['callerReference'];
		$sqlUpdUsr = "UPDATE tbl_users SET signature='".$signature."',
					refundTokenID='".$refundTokenID."',
					signatureVersion='".$signatureVersion."',
					signatureMethod='".$signatureMethod."',					
					certificateUrl='".$certificateUrl."',
					tokenID='".$tokenID."',
					callerReference='".$callerReference."' WHERE user_id='$userId'";
		$rstUpdUsr = mysql_query($sqlUpdUsr) or die(mysql_error());
		if($rstUpdUsr) { 
			$msg = "Your tokenID is successfully set.";
		}else{
			$msg = "Your tokenID is not set please try again!";
		}
	}


if($tokenID=='')
{
	$pipeline = new Amazon_FPS_CBUIRecipientTokenPipeline(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
	if($_SESSION['user_type_sess']!='5')
	{
		$pipeline->setMandatoryParameters("swapen".rand(),  
			H_ROOT."index.php?import=1", "0", "5.1", "True");
	}
	else
	{
		$pipeline->setMandatoryParameters("swapen".rand(),  
			H_ROOT."index.php?import=1", "0", "1.1", "True");
	}
	//optional parameters
	$pipeline->addParameter("paymentMethod", "CC");
	$re_URL = $pipeline->getUrl();
	header("location:".$re_URL);
}



if(isset($_POST['submit']))
   {
     $pdate=date("Y-m-d H:i:s");
     $filename=$_FILES['filename']['name'];
	 $filename = mt_rand(1,1000).$filename;
 	 if(move_uploaded_file($_FILES['filename']['tmp_name'],"sheet/".$filename))
	 {
        $handle = fopen("sheet/$filename", "r");
        $i=1;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
        {
           if($i!=1)
           {
                $sqlCat="Select category_id from tbl_category where category_name='".$data[0]."'";
				$resCat=mysql_query($sqlCat);
				$rowCat=mysql_fetch_array($resCat);
				$cat_id=$rowCat['category_id'];
                if($data[0]=="")
	            $pcode=rand(1000000000,9999999999);
                else
	            $pcode=$data[0];
	    
	 $sql1 = "INSERT INTO tbl_wholeseller_product set  category_id = '".$cat_id."',  product_code = '".addslashes($pcode)."', product_name = '".addslashes($data[1])."',product_description='".addslashes($data[2])."',quantity = '".addslashes($data[3])."', product_price = '".addslashes($data[4])."',pro_condition = '".addslashes($data[5])."',min_qty='".addslashes($data[6])."',posted_by='".$_SESSION['user_id_sess']."',posted_date='".$pdate."'"; 
      
       mysql_query($sql1);
	   
	 $subject="Your Inventory has been uploaded successfully";
	 $sqlEmail="select * from tbl_emails where email_type='Mass Upload'";
	 $resEmail=mysql_query($sqlEmail);
	 $rowEmail=mysql_fetch_array($resEmail);
	 
	 $selUser=mysql_fetch_array(mysql_query("select * from tbl_users where user_id='".$_SESSION['user_id_sess']."'"));
	 $fullname=$selUser['first_name']." ".$selUser['last_name'];
	 
	 $message=str_replace('%fname%',$selUser['first_name'],str_replace('%lname%',$selUser['last_name'],$rowEmail['email_body']));
	 $headers = "From: Swapen.com<mail@swapen.com> \r\n";
	 $headers .= 'MIME-Version: 1.0' . "\r\n";
	 $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	 mail($selUser['email'],$subject, $message, $headers);

       //$pro_id = mysql_insert_id();
       //$item_id=0;
       /*$quan=(int)$pro_quantity;
		$sqlInsItem = "INSERT INTO tbl_items_code(code,product_id,item_id,owner_id,isSold,sell_by,isWhole) VALUES ";
		for($i=1;$i<=$quan;$i++)
		{
			if($i==$quan)
			{
				$sqlInsItem .="(".rand(1000000000,9999999999).",'$pro_id','$item_id',".$_SESSION['user_id_sess'].",'0',0,1)";
			}
			else
			{
				$sqlInsItem .="(".rand(1000000000,9999999999).",'$pro_id','$item_id',".$_SESSION['user_id_sess'].",'0',0,1),";
			}
		}
		$rstInsItem = mysql_query($sqlInsItem);*/
      
      }
       $i++;
     }
     fclose($handle);
		//$Msg=1;
		
		echo "<script type='text/javascript'> window.onload=show_up;</script>";
		
	 }
 else
   {
      print "Error in Import";
   }
   }
   
 

///////////////////////////////////////////////////////////// 
?>
<div class="popup_box" style="display:none; position:absolute; background:#FFFFFF;" id="set_inventory_cf1"> 
      <div class="popup_box_in" style="height:150px;">
	  <div style="float:left; width:90%; padding:5px;">
	      Upload was Successful!<br><br>


		Final Step: Complete Your Product Listing<br><br>


		To complete your listing, you will need to fill in the remaining fields within the edit page for each item.
	  </div>
	  <div style="float:left; width:98%; padding:5px;">
	     
	      <input type="button" id="proceedbtn" value="Ok" class="yellow_btn" style="float:none; height:30px; cursor:pointer;" onclick="$('#set_inventory_cf1').hide();"/>
	  </div>
      </div>
</div>
<div id='panel'>

<div class="fulldiv" style="width:960px;">

<div class="fulldiv" style="width:250px;">

<form name="form_his" id="form_his" method="post">
<table width="98%"  border="0" cellspacing="0" class="container" style=" border-width: 0; border:none;">
  <tr class='head-tr'>
	<td>
		<div class="fulldiv">
			<div class="chat_img">&nbsp;</div>
		</div>
		<p><strong class="orangehead">Referral Commission</strong></p>
		
	</td>
  </tr>
</table>
</form>

</div>


<div class="fulldiv" style="width:700px;">

<strong class="orangehead">My Swapen</strong>
 <p>All your sold, selling, bought, buying amd other things need attentionwill be shown here.</p>

<form action=""  method="post" enctype="multipart/form-data" name="formUpload" id="formUpload" onsubmit="return checkcsv();">
  <table width="98%" border="0" cellspacing="0" class="container" style=" border-width: 0; border:none;">
  
  
  <tr>
  	<td>
	<div class="fulldiv">
		<div class="mypg_merc" >&nbsp;</div>
		<div class="mypg_msg" >&nbsp;</div>
		<div class="mypg_help" >&nbsp;</div>
		<div class="bluesml_out">Minimize All<br />
			<div class="bluearrowsml">&nbsp;</div>
		</div>
	</div>
	
  	</td>
  </tr>
  
  <tr>
  	<td>
		
	<div class="fulldiv">
		<strong class="orangehead">How to MASS - UPLOAD for WHOLSARES</strong>
		<p>This is the step - by - step process of how to upload all your products to Swapen.com</p>
		<?php if(isset($Msg))
		{?>
		<div class="row">
		  <p class="mypg_searchtxt" style="color:red;"><strong>Sheet Imported Successfully </strong></p>
		</div>
		<?php }?>
		<div class="fulldiv" style="width:700px; margin:10px 0px 10px 0px;">
			<p class="mypg_searchtxt">
			<strong>Step 1:</strong> Download the CSV File to your computer
			</p>
			<div class="pict_library">&nbsp;</div>
			<p class="mypg_searchtxt" style="clear:left;">
			<a href="download.php?f=Products.csv" class="bluelink">Click here to download the CSV file >></a>
			</p>
			<p class="mypg_searchtxt" style="clear:left;">
			Then open the file
			</p>
		</div>
	</div>
	</td>
  </tr>
  
  <tr>
  	<td>
	<div class="fulldiv">		
		<div class="fulldiv" style="width:700px; margin:10px 0px 10px 0px;">
			<p class="mypg_searchtxt">
			<strong>Step 2:</strong> Fill in the fields
			</p>
			<div class="pict_table">&nbsp;</div>
		</div>
	</div>
	</td>
  </tr>
  
  <tr>
  	<td>
	<div class="fulldiv">		
		<div class="fulldiv" style="width:700px; margin:10px 0px 10px 0px;">
			<p class="mypg_searchtxt">
			<strong>Step 3:</strong> Upload the updated CSV File
			</p>
			
			<div id="cvs_formtable">		
				  
				<div class="row">
				  <p class="mypg_searchtxt"><strong>Import Product Sheet </strong></p>
				</div>
				
				<div class="row">
				  	<div class="row_left"><label>Upload Product Sheet</label></div>
				  	<div class="row_right">
					<input type="file" name="filename" id="filename" class="inputbg" style="width:200px;">&nbsp;&nbsp;
					(Only CSV format)
				 	</div>
				</div>
				
				<div class="row">
				  <div class="row_left"><label>&nbsp;</label></div>
				  <div class="row_right">
				  <input type="submit" name="submit" id="submit" value="Import" class="yellow_btn" />
				  </div>
				</div>
			
			</div>
			
		</div>
	</div>
	</td>
  </tr>


  </table>
  <input type="hidden" name="folder" id="photofolder" value="<?php echo $photo_row['photo_id'];?>">
</form>

</div>


</div>
<script language="javascript">
  function checkcsv()
  {
      var fname=$('#filename').val();
      var ext=fname.split(".");
     // alert(ext);
      
      if(ext[1]!='csv' || fname=="")
      {
		alert("Please select csv file only.");
		return false;
      }
      else
      {
        //show_up();
		return true;
		//document.formUpload.submit();
	//return false;
      }
      
  }
</script>
<?php } ?>